//
//  String+Extension.swift
//  chat
//
//  Created by Meak Tsui on 2018/10/29.
//  Copyright © 2018 Meak Tsui. All rights reserved.
//

import Foundation
import CommonCrypto

extension String {
    public func substring(s: Int, _ e: Int? = nil) -> String {
        let start = s >= 0 ? self.startIndex : self.endIndex
        let startIndex = self.index(start, offsetBy: s)
        
        var end: String.Index
        var endIndex: String.Index
        if(e == nil){
            end = self.endIndex
            endIndex = self.endIndex
        } else {
            end = e ?? 0 >= 0 ? self.startIndex : self.endIndex
            endIndex = self.index(end, offsetBy: e!)
        }
        
        let range = startIndex..<endIndex
        return String(self[range])
        
    }
    
    public func isPhoneNumber() -> Bool {
        if self.count == 0 {
            return false
        }
        let mobile = "1[34578]([0-9]){9}"
        let regexMobile = NSPredicate(format: "SELF MATCHES %@",mobile)
        return regexMobile.evaluate(with: self)
    }
    
    
    public func toDate(fmtStr:String = "yyyy-MM-dd HH:mm:ss") -> Date? {
        let formatter = DateFormatter()
        formatter.dateFormat = fmtStr
        return formatter.date(from: self)
    }
    
    public func md5() -> String {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        free(result)
        return String(format: hash as String)
    }
}
